package com.zxjbyte.yiyi.extension.job.util;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.zxjbyte.yiyi.extension.job.core.processor.JobHandler;
import com.zxjbyte.yiyi.framework.common.constant.StringPool;
import com.zxjbyte.yiyi.framework.common.exception.ServiceException;
import com.zxjbyte.yiyi.framework.common.util.ClassXUtils;
import com.zxjbyte.yiyi.framework.common.util.ValidationUtil;

/**
 * @Author zhangxingjia
 * @Date 2024/1/4 16:26
 * @Version: 1.0
 */
public class JobUtil {

    /**
     * 检测处理器是否合法
     *
     * @param jobHandler
     */
    public static String checkJobHandler(String jobHandler){
        if(StrUtil.contains(jobHandler, StringPool.DOT)){
            try {
                Class.forName(jobHandler);
            } catch (ClassNotFoundException e) {
                throw new ServiceException("任务处理器 ["+ jobHandler +"] 不存在，请检查类名是否正确。");
            }
        } else {
            ValidationUtil.assertTrue(SpringUtil.getApplicationContext().containsBean(jobHandler),
                    "未找到任务处理器 [{}]，请确认是否已正确注册到 Spring 容器。", jobHandler);
            Class<?> type = SpringUtil.getApplicationContext().getType(jobHandler);
            ValidationUtil.assertTrue(ClassXUtils.isAssignable(JobHandler.class, type), "任务处理器 [{}] 类型错误，" +
                    "必须实现IJobHandler接口。", jobHandler);
            return ClassUtil.getClassName(type, false);
        }
        return jobHandler;
    }
}
